<!--
  功能：功能描述
  作者：kangjie
  邮箱：kangjie@briup.com
  时间：2021年07月13日 16:22:33
  版本：v1.0
  修改记录：
  修改内容：
  修改人员：
  修改时间：
-->
<template>
  <div class>
    <!-- 添加查询按钮 -->
    <div>
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-button type="primary" @click="toAdd">添加</el-button>
        <el-form-item style="margin-left:10px">
          <el-input v-model="searchForm.name" placeholder="请输入名称" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="正常" value="正常"></el-option>
            <el-option label="下架" value="下架"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select placeholder="请选择栏目" v-model="searchForm.productCategoryId" clearable>
            <el-option
              v-for="item in categoryData"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="Onsearch">查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!--表格-->
    <div>
      <el-table :data="productData" stripe style="width: 100%">
        <el-table-column type="index" :index="1" label="序号" width="60"></el-table-column>
        <el-table-column prop="id" label="产品编号" width="180"></el-table-column>
        <el-table-column prop="name" label="名称"></el-table-column>
        <el-table-column label="图片">
          <template slot-scope="scope">
            <el-image
              style="width:30px;height:30px"
              :src="scope.row.photo"
              :preview-src-list="[scope.row.photo]"
            ></el-image>
          </template>
        </el-table-column>
        <el-table-column prop="price" label="价格"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-tag type="success" v-if="scope.row.status==='正常'">{{scope.row.status}}</el-tag>
            <el-tag type="danger" v-else>{{scope.row.status}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="category.name" label="所属栏目"></el-table-column>
        <el-table-column label="操作" width="120" align="center">
          <template slot-scope="scope">
            <el-button @click="toEdit(scope.row)" type="text" size="small">编辑</el-button>
            <el-button
              type="text"
              v-if="scope.row.status==='下架'"
              class="offline"
              @click="onLine(scope.row.id)"
            >上架</el-button>
            <el-button type="text" v-else class="online" @click="offLine(scope.row.id)">下架</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页 -->
    <div>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="params.page"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="params.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>
    <!--模态框 -->
    <el-dialog :title="title" :visible.sync="visible" @close="toClose">
      <el-form :model="form" :rules="rules" ref='ruleForm'>
        <el-form-item label="产品名称" :label-width="formLabelWidth" prop="name">
          <el-input v-model="form.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="所属栏目" :label-width="formLabelWidth" prop="productCategoryId">
          <el-select v-model="form.productCategoryId" placeholder="请选择栏目">
            <el-option
              v-for="item in categoryData"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="价格" :label-width="formLabelWidth" prop="price">
          <el-input v-model="form.price" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="封面" :label-width="formLabelWidth" prop="photo">
          <el-upload
            class="avatar-uploader"
            :action="uploadFileURL"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl" :src="form.photo" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="产品描述" :label-width="formLabelWidth" prop="description">
          <el-input type="textarea" v-model="form.description"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="visible = false">取 消</el-button>
        <el-button type="primary" @click="toSave">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { pageQuery } from "@/api/column.js";
import { showFileURL, uploadFileURL } from "@/utils/config";
import {
  pageQuery as pageQueryPro,
  saveOrUpdate,
  online,
  offline,
  deleteById
} from "@/api/product";
export default {
  // 组件名称
  name: "demo",
  // 组件参数 接收来自父组件的数据
  props: {},
  // 组件状态值
  data() {
    return {
      searchForm: {},
      showFileURL,
      uploadFileURL,
      imageUrl: "",
      title: "",
      formLabelWidth: "80px",
      visible: false,
      form: {},
      productData: [],
      params: {
        page: 1,
        pageSize: 10
      },
      categoryData: [],
      total: 0,
      rules: {
        name: [{ required: true, message: "请输入栏目名称", trigger: "blur" }],
        productCategoryId: [
          { required: true, message: "请选择所属栏目", trigger: "blur" }
        ],
        price: [{ required: true, message: "价格不能为空", trigger: "blur" }],
        photo: [{ required: true, message: "图片不能为空", trigger: "blur" }]
      }
    };
  },
  // 计算属性
  computed: {},
  // 侦听器
  watch: {
    params: {
      handler() {
        this.pageQueryPro();
      },
      deep: true
    }
  },
  // 组件方法
  methods: {
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
      this.form.photo = showFileURL + res.data.id;
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    // 去编辑
    toEdit(row) {
      this.form = { ...row };
      this.title = "修改产品信息";
      this.visible = true;
      this.imageUrl = this.form.photo;
    },
    // 去添加
    toAdd() {
      this.visible = true;
      this.title = "添加产品信息";
      this.form = {};
      this.imageUrl = "";
    },
    // 模糊查询
    Onsearch() {
      this.pageQueryPro();
    },
    // 查询栏目分类信息
    async category() {
      let res = await pageQuery(this.params);
      // console.log(res);
      this.categoryData = res.data.list;
    },
    // 模糊分页查询产品相关信息
    async pageQueryPro() {
      let temp = {
        ...this.params,
        ...this.searchForm
      };
      for (let key in temp) {
        if (!temp[key]) {
          delete temp[key];
        }
      }
      let res = await pageQueryPro(temp);
      // console.log(res);
      this.productData = res.data.list;
      this.total = res.data.total;
    },
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      this.params.pageSize = val;
      this.params.page = 1;
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.params.page = val;
    },
    // 上架
    async onLine(id) {
      let res = await online({ id });
      this.$notify.success({
        title: "上架成功",
        message: res.message,
        type: "success"
      });
      this.pageQueryPro();
    },
    // 下架
    async offLine(id) {
      let res = await offline({ id });
      this.$notify.success({
        title: "下架成功",
        message: res.message,
        type: "success"
      });
      this.pageQueryPro();
    },
    // 去保存
    toSave() {
      this.$refs['ruleForm'].validate(async valid => {
        if (valid) {
          // alert("submit!");
        let res = await saveOrUpdate(this.form);
        this.$notify.success({
          title:"更新成功",
          message:res.message,
          type:"success"
        });
        this.toClose();
        this.pageQueryPro();
        } else {
          // console.log("error submit!!");
          return false;
        }
      });
      // console.log(res);
    },
    toClose() {
      this.$refs['ruleForm'].resetFields();
      setTimeout(()=>{
        this.visible=false
      },100);
      for(let key in this.form){
        this.form[key]='';
      }
      this.imageUrl='';
    }
  },
  // 以下是生命周期钩子
  /**
   * 组件实例创建完成，属性已绑定，但DOM还未生成，$ el属性还不存在
   */
  created() {
    this.category();
    this.pageQueryPro();
  },
  /**
   * el 被新创建的 vm.$ el 替换，并挂载到实例上去之后调用该钩子。
   * 如果 root 实例挂载了一个文档内元素，当 mounted 被调用时 vm.$ el 也在文档内。
   */
  mounted() {},
  /**
   * 实例销毁之前调用。在这一步，实例仍然完全可用。
   */
  beforeDestroy() {},
  /**
   * Vue 实例销毁后调用。调用后，Vue 实例指示的所有东西都会解绑定，
   * 所有的事件监听器会被移除，所有的子实例也会被销毁。
   */
  destroyed() {}
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<!--使用了scoped属性之后，父组件的style样式将不会渗透到子组件中，-->
<!--然而子组件的根节点元素会同时被设置了scoped的父css样式和设置了scoped的子css样式影响，-->
<!--这么设计的目的是父组件可以对子组件根元素进行布局。-->
<style >
.offline {
  color: #759cc2;
}
.online {
  color: #ed8e9a;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
